Let's say we have class A as a parent class, and class C that extends it.
class A
{
void m()
{
System.out.println("A.m");
}
}
class C extends A
{
@Override
void m()
{
System.out.println("C.m");
}
}
What's the difference between reference A a
and C c
when we use them to point to the same object type, for example A a = new C();
and C c = new C();
?
From this question: Java inheritance vs. C# inheritance, it looks like that as a
and c
points to object type of C, and there seems no difference in using them.
I tested this code, and they all prints C.m
.
class inherit {
void x(A a)
{
a.m();
}
public static void main(String[] args) {
System.out.println("hello");
A a = new C();
C c = new C();
a.m();
c.m();
new inherit().x(a);
new inherit().x(c);
}
}
Copyright Notice:Content Author:「prosseek」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/14917903/the-difference-between-c-c-new-c-and-a-c-new-c-when-c-is-a-subclass